/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package shmallarchitect.jpa.controllers;

import java.util.List;
import javax.annotation.Resource;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.PersistenceUnit;
import javax.persistence.Query;
import javax.persistence.EntityNotFoundException;
import javax.transaction.UserTransaction;
import shmallarchitect.jpa.controllers.exceptions.NonexistentEntityException;
import shmallarchitect.jpa.controllers.exceptions.RollbackFailureException;
import shmallarchitect.jpa.entities.Category;
import shmallarchitect.jpa.entities.Locum;
import java.util.HashSet;
import java.util.Set;

/**
 *
 * @author jaccus
 */
public class CategoryJpaController {
    @Resource (mappedName="utx")
    private UserTransaction utx = null;
    @PersistenceUnit(unitName = "ShmallArchitectPU")
    private EntityManagerFactory emf = null;

    public EntityManager getEntityManager() {
        return emf.createEntityManager();
    }

    public void create(Category category) throws RollbackFailureException, Exception {
        if (category.getLocums() == null) {
            category.setLocums(new HashSet<Locum>());
        }
        EntityManager em = null;
        try {
            utx.begin();
            em = getEntityManager();
            Set<Locum> attachedLocums = new HashSet<Locum>();
            for (Locum locumsLocumToAttach : category.getLocums()) {
                locumsLocumToAttach = em.getReference(locumsLocumToAttach.getClass(), locumsLocumToAttach.getId());
                attachedLocums.add(locumsLocumToAttach);
            }
            category.setLocums(attachedLocums);
            em.persist(category);
            for (Locum locumsLocum : category.getLocums()) {
                locumsLocum.getCategories().add(category);
                locumsLocum = em.merge(locumsLocum);
            }
            utx.commit();
        } catch (Exception ex) {
            try {
                utx.rollback();
            } catch (Exception re) {
                throw new RollbackFailureException("An error occurred attempting to roll back the transaction.", re);
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void edit(Category category) throws NonexistentEntityException, RollbackFailureException, Exception {
        EntityManager em = null;
        try {
            utx.begin();
            em = getEntityManager();
            Category persistentCategory = em.find(Category.class, category.getId());
            Set<Locum> locumsOld = persistentCategory.getLocums();
            Set<Locum> locumsNew = category.getLocums();
            Set<Locum> attachedLocumsNew = new HashSet<Locum>();
            for (Locum locumsNewLocumToAttach : locumsNew) {
                locumsNewLocumToAttach = em.getReference(locumsNewLocumToAttach.getClass(), locumsNewLocumToAttach.getId());
                attachedLocumsNew.add(locumsNewLocumToAttach);
            }
            locumsNew = attachedLocumsNew;
            category.setLocums(locumsNew);
            category = em.merge(category);
            for (Locum locumsOldLocum : locumsOld) {
                if (!locumsNew.contains(locumsOldLocum)) {
                    locumsOldLocum.getCategories().remove(category);
                    locumsOldLocum = em.merge(locumsOldLocum);
                }
            }
            for (Locum locumsNewLocum : locumsNew) {
                if (!locumsOld.contains(locumsNewLocum)) {
                    locumsNewLocum.getCategories().add(category);
                    locumsNewLocum = em.merge(locumsNewLocum);
                }
            }
            utx.commit();
        } catch (Exception ex) {
            try {
                utx.rollback();
            } catch (Exception re) {
                throw new RollbackFailureException("An error occurred attempting to roll back the transaction.", re);
            }
            String msg = ex.getLocalizedMessage();
            if (msg == null || msg.length() == 0) {
                Long id = category.getId();
                if (findCategory(id) == null) {
                    throw new NonexistentEntityException("The category with id " + id + " no longer exists.");
                }
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void destroy(Long id) throws NonexistentEntityException, RollbackFailureException, Exception {
        EntityManager em = null;
        try {
            utx.begin();
            em = getEntityManager();
            Category category;
            try {
                category = em.getReference(Category.class, id);
                category.getId();
            } catch (EntityNotFoundException enfe) {
                throw new NonexistentEntityException("The category with id " + id + " no longer exists.", enfe);
            }
            Set<Locum> locums = category.getLocums();
            for (Locum locumsLocum : locums) {
                locumsLocum.getCategories().remove(category);
                locumsLocum = em.merge(locumsLocum);
            }
            em.remove(category);
            utx.commit();
        } catch (Exception ex) {
            try {
                utx.rollback();
            } catch (Exception re) {
                throw new RollbackFailureException("An error occurred attempting to roll back the transaction.", re);
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public List<Category> findCategoryEntities() {
        return findCategoryEntities(true, -1, -1);
    }

    public List<Category> findCategoryEntities(int maxResults, int firstResult) {
        return findCategoryEntities(false, maxResults, firstResult);
    }

    private List<Category> findCategoryEntities(boolean all, int maxResults, int firstResult) {
        EntityManager em = getEntityManager();
        try {
            Query q = em.createQuery("select object(o) from Category as o");
            if (!all) {
                q.setMaxResults(maxResults);
                q.setFirstResult(firstResult);
            }
            return q.getResultList();
        } finally {
            em.close();
        }
    }

    public Category findCategory(Long id) {
        EntityManager em = getEntityManager();
        try {
            return em.find(Category.class, id);
        } finally {
            em.close();
        }
    }

    public int getCategoryCount() {
        EntityManager em = getEntityManager();
        try {
            return ((Long) em.createQuery("select count(o) from Category as o").getSingleResult()).intValue();
        } finally {
            em.close();
        }
    }

}
